<?php
namespace app\index\controller;
use app\CommonController;
use app\index\Validate\LoginValidate;
use app\service\MemberService;
use app\service\MemberCoinService;
use app\service\TemplateService;
use think\db\exception\DbException;
use think\facade\Cache;
use think\captcha\facade\Captcha;
use think\exception\ValidateException;
use think\facade\Cookie;
use think\facade\Session;
use think\helper\Str;
use think\facade\Db;
class Login extends CommonController
{
    public function index()
    {
        if (cookie("email")) {
          return  $this->redirect("/member");
        }
       return $this->fetch("login");
    }

    public function register()
    {
       $this->assign("verify_code",$this->request->param("verify_code"));
       return $this->fetch("register");
    }

    public function forget()
    {
        if ($this->request->post()) {
           $post = $this->request->post();
            try {
                validate(LoginValidate::class)->scene("forget")->check($post);
            } catch (ValidateException $e) {
                throw new ValidateException($e->getError());
            }
            $memberService = $this->app->make(MemberService::class);
            $member = $memberService->getOne(["email"=>$post["email"]],"status");
            if (empty($member)) {
                $this->error("用户不存在");
            }
            $member->passwd = $post["password"];
            $res = $member->save();
            if ($res) {
                $this->success("密码重置成功");
            } else {
                $this->error("密码充值失败");
            }

        } else {
            return $this->fetch("forget");
        }
    }

    public function verify()
    {
        return Captcha::create();
    }


    public function sendEmailCode()
    {
        $post = $this->request->post();
        try {
            validate(LoginValidate::class)->scene("send_email")->check($post);
        } catch (ValidateException $e) {
            throw new ValidateException($e->getError());
        }
        $code = Str::random(4,1);
        $email = $post["email"];
        $sendKey =sprintf("%s%s",config("constant.email_register_key"),$email);
        $template = $this->app->make(TemplateService::class);
        $template->setMask(config("constant.email_verify_mask_key"))
            ->setReplace(["code"=>$code])
            ->setAddress($email);
        $template->sendEmail();
        Cache::store('redis')->set($sendKey,$code,600);
        $this->success("发送成功");
    }

    public function doRegister()
    {
        $post = $this->request->post();
        try {
            validate(LoginValidate::class)->scene("register")->check($post);
        } catch (ValidateException $e) {
            throw new ValidateException($e->getError());
        }
        $memberService = $this->app->make(MemberService::class);
        $pid =0;
        $tree="";
        if (!empty($post["invite_code"])) {
            $parentInfo =$memberService->getOne(["invite_code" => $post["invite_code"]],"id,tree");
            if (!empty($parentInfo)) {
                $pid = $parentInfo["id"] ?? 0;
                $tree = $parentInfo["tree"] ? $parentInfo["tree"]."|".$pid :"";
            }
        }
        $ip2region = new \Ip2Region();
        $ip = $this->request->ip();
        $address = $ip2region->simple($ip);
        $data["pid"] = $pid;
        $data["invite_code"] = Str::random(6);
        $data["email"] = $post["email"];
        $data["passwd"] = $post["passwd"];
        $data["tree"] = $tree;
        $data["login_ip"] =  $ip ;
        $data["login_address"] =$address;
        try {

          $memberService->save($data);

        } catch (\Exception $e) {
            throw new DbException($e->getMessage());
        }
        $this->success("注册成功");

    }

    public function doLogin()
    {
        $post = $this->request->post();
        $memberService = $this->app->make(MemberService::class);
        $remember = $post["remember"] ?? 0;
        $memberService->login($post["email"],$post["password"],$remember);
        $this->success("登录成功","/member");
    }

    public function logout()
    {
        Session::destroy();
        Cookie::delete('email');
        return $this->redirect("/");
    }
}